<?php
namespace app\common\model;
use app\common\traits\Models;
use think\Model;
use think\facade\{
    App,Request,Config
};
class ComCodeimg extends Model
{
    use Models;
    protected $readonly = [];
    protected $auto     = [];
    protected $insert   = ['ip','end_time'];
    protected $update   = [];

    //设置Ip
    protected function setIpAttr()
    {
        return Request::ip(1);
    }

    //设置过期时间
    protected function setEndTimeAttr()
    {
        return Request::time()+Config::get('type.expire_time');
    }

    /**
     * 保存验证码到数据库
     * @param  [type] $code  [验证码]
     * @param  [type] $token [对应token]
     * @return [type]        [description]
     */
    public function saveCode($code, $token){
        $domain = $_SERVER['HTTP_HOST'];
        $arr = explode(".",$domain);
        if($arr[0]!='api' && $arr[0]!='192') return true;

        $this::destroy(function($query)use($token){$query->where('token',$token)->delete();});
        $this::create(['code'=>$code, 'token'=>$token]);
        return true;
    }

    /**
     * 验证图形验证码
     * @param  [type] $img_token [description]
     * @param  [type] $code  [description]
     * @return [type]        [description]
     */
    public function checkCode($img_token, $code){
        $rs = $this::get(function($query)use($img_token,$code){
            $query->where([['token','=',$img_token],['code','=',$code],['end_time','>',Request::time()]]);
        });
        if($rs){
            $rs->delete(true);
            return true;
        }
        //session('js.name','img_token');
        $this->error = '图形验证码错误';
        return false;
    }
}
